<template>
	<el-dialog title="设置商户转换汇率" width="70%" :visible.sync="dialogVisible" :close-on-click-modal="false">
		<d2-crud
      selection-row
      :options="mainTable.options"
      :index-row="mainTable.indexRow"
      :columns="mainTable.columns"
      :data="mainTable.list"
      :loading="mainTable.loading"
      :selection-row="mainTable.allowSelect"
      @current-change="onMainCurrentChange"
      @cell-data-change="handleCellDataChange"
    ></d2-crud>
    <!-- :rowHandle="mainTable.rowHandle" -->

    <!-- layout="total, sizes, prev, pager, next, jumper" -->
    <template slot="footer">
      <el-pagination
        @size-change="handleMainSizeChange"
        @current-change="handleMainPageChange"
        :current-page="mainTable.pagination.currentPage"
        :page-sizes="mainTable.pagination.pageSizes"
        :page-size="mainTable.pagination.pageSize"
        :page-count="mainTable.pagination.pageCount"
        :total="mainTable.pagination.total"
        layout="total"
        :background="true"
        >
      </el-pagination>
    </template>

    <div slot="footer" class="dialog-footer">
      <el-button @click="close" size="small">取 消</el-button>
      <el-button type="primary" @click="submit" size="small" :loading="loading"  v-if="$options.filters['checkButtonAccess']('statMonthlyTrade-currencyTrans')">提 交</el-button>
    </div>
	</el-dialog>
</template>

<script>
import ApiMain from '@/api/statMonthlyTrade';
import util from '@/libs/util.js';

export default {
  name: 'mch-announcement',
  mixins: [
  ],
  components: {
  },
  data () {
    return {

      mainQuery: {
        statMonth: '',
        channelId: '',
      },

      mainTable: {
        loading: false,
        options: {
          border             : true,
          stripe             : true,
          highlightCurrentRow: true,
          emptyText          : '暂无数据',
          size               : 'mini',
        },

        indexRow: null,
        allowSelect: false,
        columns: [
          // {title: 'id', key: 'id', align: 'center', showOverflowTooltip: true},
          {title: '年月', key: 'statMonth', align: 'center', showOverflowTooltip: true},
          {title: '商户号', key: 'mchNo', align: 'center', showOverflowTooltip: true},
          {title: '商户名称', key: 'mchName', align: 'center', showOverflowTooltip: true},
          {title: '交易手续费', key: 'serviceFee', align: 'center', showOverflowTooltip: true, formatter: this.formatPrice},
          {title: '商户结算金额', key: 'settleAmount', align: 'center', showOverflowTooltip: true, formatter: this.formatPrice},
          {title: '通道结算币种', key: 'channelSettleCurrency', align: 'center', showOverflowTooltip: true},
          {title: '商户结算币种', key: 'settleCurrency', align: 'center', showOverflowTooltip: true},
          {title: '一级分润', key: 'salesCommission1', align: 'center', showOverflowTooltip: true, formatter: this.formatPrice},
          {title: '二级分润', key: 'salesCommission2', align: 'center', showOverflowTooltip: true, formatter: this.formatPrice},
        	{title: '通道币种转换汇率', key: 'currencyTransRate', width: '120', align: 'center', showOverflowTooltip: true, formatter: this.formatRate, component: {
            name: 'el-input',
            size: 'mini',
            type: 'number'
          }},
        ],
        rowHandle: {
          width: '200',
          align: 'center',
          fixed: 'right',
          custom: [
            {
              text: '设置通道币种转换汇率',
              type: 'primary',
              size: 'mini',
              emit: 'custom-emit-handle-set-rate'
            },
          ]
        },
        list: [],
        pagination: {
          currentPage: 1,
          pageSize   : 50,
          total      : 0,
          pageSizes  : [50, 100, 200]
        },
      },

      form: {},
      loading: false,
      dialogVisible: false,

    }
  },
  mounted () {
    
  },
  beforeDestroy () {
  },
  methods: {
  	formatPrice (row, col, val, index) {
      return (this.emptyToZero(val) / 100).toFixed(2);
    },

    formatRate (row, col, val, index) {
      return (this.emptyToZero(val) / 1000000).toFixed(2) + '%';
    },

    emptyToZero (val = null) {
      return !val ? 0 : val;
    },

  	show (row) {
  		this.mainQuery.statMonth = row.statMonth;
  		this.mainQuery.channelId = row.channelId;
  		this.dialogVisible = true;
      this.form.id = row.id;
      this.form.data = [];
  		this.resetMainData();
  	},

    renderMainData (re) {
      let data = [];
      re.list.forEach((item, index) => {
        re.list[index].currencyTransRate = item.currencyTransRate / 1000000;
        data.push({id: item.id, currencyTransRate: re.list[index].currencyTransRate});
      });
      this.mainTable.list = re.list;
      this.mainTable.pagination.total = re.total;
      this.form.data = data;
    },

    handleSearch () {
      this.mainTable.pagination.currentPage = 1;
      this.fetchMainData();
    },

    handleMainSizeChange (val) {
      this.mainTable.pagination.pageSize = val;
      this.mainTable.pagination.currentPage = 1;
      this.fetchMainData()
    },

    handleMainPageChange (val) {
      this.mainTable.pagination.page = val;
      this.fetchMainData()
    },

    buildMainQuery () {

      var query = {
        page  : this.mainTable.pagination.currentPage,
        limit : this.mainTable.pagination.pageSize,
        search: this.mainQuery,
      };

      return query;
    },

    resetMainData () {
      this.fetchMainData();
    },

    async fetchMainData () {

      this.mainTable.loading = true;

      try {
        var re = await ApiMain.tradeChannelList(this.buildMainQuery());
        this.renderMainData(re);
      } catch (err) {}

      this.mainTable.loading = false;

    },

    onMainCurrentChange (now, old) {
      this.mainTable.current = now;
    },

    handleCellDataChange ({ rowIndex, key, value, row }) {
      let form = Object.copy(this.form);
      let val = 0;
      if (typeof value == 'object') {
        val = value.value == '' ? 0 : value.value;
      } else {
        val = value;
      }
      form.data[rowIndex][key] = val;
      this.form = form;
      console.log(form);
    },

    close () {
      this.dialogVisible = false;
      this.$emit('dialog-close');
    },

    verifyForm () {
      let pattern = /^(([1-9]{1}\d*)|(0{1}))(\.\d{1,6})?$/;
      for (let i in this.form.data) {
        // if (this.form.data[i].currencyTransRate < 0 || !pattern.test(this.form.data[i].currencyTransRate)) {
        if (this.form.data[i].currencyTransRate < 0) {
          this.$message({message: '汇率设置应大于0且最多6位小数', type: 'error'});
          return false;
        }
      }
      return true;
    },

    async submit () {
      this.$confirm('确定转换并计算损益?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.doSubmit();
      });
    },

    async doSubmit () {
      if (! this.verifyForm()) return false;
      if (this.form.data.length == 0) {
        this.$message({message: '没有设置汇率', type: 'success'});
        return;
      }
      this.loading = true;

      try {
        await this.submitSetCurrencyTrans();
        this.$message({message: '设置成功', type: 'success'});
        this.close();
      } finally {
        this.loading = false;
      }
    },

    async submitSetCurrencyTrans () {
      let form = null;
      form = this.form;
      for (let i in form.data) {
        form.data[i].currencyTransRate = form.data[i].currencyTransRate * 1000000;
      }
      await ApiMain.currencyTrans(form);
    }

  }
}
</script>